package TestPaperSystem.mulitEditorOnline.service.Impl;

import TestPaperSystem.Dto.PageUtils_VO;
import TestPaperSystem.mulitEditorOnline.pojo.DocumentEntity;
import TestPaperSystem.mulitEditorOnline.service.EditOnlineService;
import TestPaperSystem.utils.idGetter.IdGetter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.SubSuperScript;
import com.spire.doc.documents.UnderlineStyle;
import com.spire.doc.fields.TextRange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.text.DecimalFormat;
import java.util.List;

@Service
public class EditOnlineServiceImpl implements EditOnlineService {

    @Autowired
    private MongoTemplate mongo;

    private final Document doc = new Document();
    @Override
    public String saveFileAsOnlineEdit(MultipartFile file , String userName,String userId) throws Exception{
        if(file == null)
            throw new NullPointerException("传入文件为空");


        String file_name = file.getOriginalFilename();


        DocumentEntity documentEntity = new DocumentEntity();

        documentEntity.setUploadFileName(file_name.substring(0,file_name.lastIndexOf(".")));
        documentEntity.setUploadUserId(userId);
        documentEntity.setUploadUserName(userName);

        String file_type = file_name.substring(file_name.lastIndexOf(".") + 1,file_name.length());

        if(file_type.equals("doc")){
            doc.loadFromStream(file.getInputStream(), FileFormat.Doc);
        }else if(file_type.equals("docx")){
            doc.loadFromStream(file.getInputStream(),FileFormat.Docx);
        }

        //定义的r,g,b,a 代表三色元及透明度 str做临时变量
        String r = "",g = "",b = "",a = "",str;

        StringBuilder elements = new StringBuilder();

        //文章段落数
        int counts = doc.getSections().get(0).getParagraphs().getCount();

        for (int i = 0; i < counts; i++) {

            elements.append("<p>");

            Paragraph paragraph = doc.getSections().get(0).getParagraphs().get(i);


            int paragraph_childNodes = paragraph.getChildObjects().getCount();

            //遍历段落子节点
            for (int j = 0; j < paragraph_childNodes; j++) {

                Object obj = paragraph.getChildObjects().get(j);
                if(obj instanceof TextRange){

                    elements.append("<span style= \"");

                    TextRange text = (TextRange) obj;

                    //获取文本颜色
                    Color color = text.getCharacterFormat().getTextColor();
                    if(color.getRGB() != 0){
                        elements.append("background-color:" + getColorStr(r,g,b,a,color) + ";");
                    }

                    //字体倾斜
                    boolean italic = text.getCharacterFormat().getItalic();
                    if(italic){
                        elements.append("font-style: italic;");
                    }

                    //文本背景
                    Color highlightColor = text.getCharacterFormat().getHighlightColor();
                    if(highlightColor.getRGB() != 0){

                        elements.append("background-color:" + getColorStr(r,g,b,a,color) + ";");
                    }

                    //字体大小
                    String fontSize = String.format("%.0f",text.getCharacterFormat().getFontSize()) + "px;";
                    elements.append("font-size: " + fontSize);

                    //字体类型
                    String fontFamily = text.getCharacterFormat().getFontName();
                    elements.append("font-family: " + fontFamily + ";");
                    elements.append("\">");

//----------------------------分割线 style 分布在最外层 字体加粗、下划线、删除线计算----------------------------
                    str = text.getText();

                    //字体粗体
                    if(text.getCharacterFormat().getBold()){
                        str = "<strong>" + str + "</strong>";
                    }

                    //字体删除线
                    boolean strikeout = text.getCharacterFormat().isStrikeout();
                    if(strikeout){
                        str += "<s>" + str + "</s>";
                    }

                    //字体下划线
                    boolean underLineStyle = text.getCharacterFormat().getUnderlineStyle() == UnderlineStyle.Single;
                    if(underLineStyle){
                        str += "<u>" + str + "</u>";
                    }
//                    下标为2，上标为1 subSuperScript
                    SubSuperScript subSuperScript = text.getCharacterFormat().getSubSuperScript();
                    if(subSuperScript.getValue() == 1){
                        str = "<sup>" + str + "</sup>";
                    }else if(subSuperScript.getValue() == 2){
                        str = "<sub>" + str + "</sub>";
                    }

                    elements.append(str + "</span>");
                }
            }
            elements.append("</p>\n");
        }

        documentEntity.setContent(elements.toString());

        documentEntity.setDocId(IdGetter.getInstance().getEntityId());

        return mongo.save(documentEntity, "document").get_id()== null ? "null":documentEntity.getDocId();
    }

    private String getColorStr(String r ,String g , String b , String a , Color color){
        r = Integer.toHexString(color.getRed()).toUpperCase();
        g = Integer.toHexString(color.getGreen()).toUpperCase();
        b = Integer.toHexString(color.getBlue()).toUpperCase();
        a = Integer.toHexString(color.getAlpha()).toUpperCase();

        r = r.length() == 1 ? "0" + r : r;
        g = g.length() ==1 ? "0" +g : g;
        b = b.length() == 1 ? "0" + b : b;
        a = a.length() == 1 ? "0" + a : a;
        r = r.toUpperCase();
        g = g.toUpperCase();
        b = b.toUpperCase();
        a = a.toUpperCase();
        return  "#" + r + g + b + a;
    }

    @Override
    public DocumentEntity getDocContentById(String docId) throws Exception {

        Query query = new Query(Criteria.where("docId").is(docId));

        DocumentEntity document = mongo.findOne(query, DocumentEntity.class, "document");

        if(document == null){
            throw new Exception("数据不存在");
        }
        return document;
    }

    @Override
    public Page getPageData(PageUtils_VO page) throws Exception {

        Page result = new Page();

        Query query = new Query();
        query.skip((page.getCurrentPage() - 1) * page.getSize() ) .limit(page.getSize());
        long total = mongo.count(query,"document");
        List<DocumentEntity> documentEntities = mongo.find(query, DocumentEntity.class);

        result.setTotal(total);
        result.setRecords(documentEntities);
        result.setSize(page.getSize());
        result.setCurrent(page.getCurrentPage());
        return result;
    }
}
